Vue.component("yl-upload", {
  template: `<div>
    <div class="preview" v-if="Picture_URL">
        <el-image ref="FImage" class="el-upload-list__item-thumbnail" style="width: 148px; height: 148px" :preview-src-list="[base64?Picture_URL:base + Picture_URL]" :src="base64?Picture_URL:base + Picture_URL" fit="contain"></el-image>
        <span class="el-upload-list__item-actions">
            <span @click="handlePictureCardPreview('FImage')"><i class="el-icon-zoom-in"></i></span>
            <span @click="handleRemove"><i class="el-icon-delete"></i></span>
        </span>
    </div>
    <el-upload :disabled="loading" v-else class="upload-demo" :show-file-list="false" :on-change="upload"
        list-type="picture-card" action="" accept="image/*" :auto-upload="false">
        <i slot="default" :class="loading?'el-icon-loading':'el-icon-plus'"></i>
        <div v-if="!unslider" class="el-upload__tip" slot="tip">
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
            <el-slider :min="1" style="width:148px" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" fit="contain" :src="dialogImageUrl">
    </el-dialog></div>`,
  props: {
    value: {
      type: String,
      default: "",
    },
    base: {
      type: String,
      default: "",
    },
    base64: {
      type: Boolean,
      default: false,
    },
    unslider: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      Picture_URL: this.value,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      quality: 100,
    };
  },
  watch: {
    value(newVal) {
      this.Picture_URL = newVal;
    },
    Picture_URL(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    formatTooltip(val) {
      return "图片压缩比例：" + val + "%";
    },
    upload({ raw }) {
      const that = this;
      new Compressor(raw, {
        quality: that.quality / 100,
        success(file) {
          that.loading = true;
          const formData = new FormData();
          formData.append("file", file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            if (!that.base64) {
              $.ajax({
                type: "POST",
                // url: DomainName + "/BusinessPIC",
                url:
                  "https://service.kdddy.cn/donghuiwar/svysj" + "/BusinessPIC",
                data: {
                  Data: e.target.result,
                  DataLength: file.size,
                  FileName: file.name,
                  logo: true,
                },
                complete: function (XMLHttpRequest) {
                  that.loading = false;
                  if (
                    XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT"
                  ) {
                    window.parent.document.location.href =
                      absolutepath() +
                      XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                success: function (Result) {
                  console.log(Result);

                  if (Result.Status == "success") {
                    Result.Picture_Url = "/1737793178095.jpeg";
                    that.Picture_URL = Result.Picture_Url;
                    that.$message.success("上传成功");
                  } else {
                    that.$message.error("上传失败");
                  }
                },
                error: function () {
                  that.$message.error("操作失败，请稍后再试");
                },
                dataType: "json",
              });
            } else {
              console.log(e);

              that.Picture_URL = e.target.result;
              that.loading = false;
            }
          };
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    handlePictureCardPreview(formName) {
      this.$refs[formName].showViewer = true;
    },
    handleRemove() {
      this.Picture_URL = "";
      this.$emit("remove");
    },
  },
});
new Vue({
  el: "#app",
  data() {
    const validator = (rule, value, callback) => {
      if (value == "<p><br></p>") {
        callback(new Error('请输入内容'));
      } else {
        callback();
      }
    }
    return {
      fileList: [],
      props: {
        multiple: true,
        label: "New_Type_Name",
        value: "New_Type_SerialNumber",
      },
      options: [],
      News_Type: [
        {
          value: "0",
          label: "产业技术",
        },
        {
          value: "1",
          label: "文化宣传",
        },
        {
          value: "2",
          label: "产品展示",
        },
        {
          value: "3",
          label: "政策",
        },
        {
          value: "4",
          label: "法规",
        },
      ],
      rules: {
        News_Name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        News_Main: [{ required: true, validator: validator, trigger: 'blur' }],
      },
      type: [],
      form: {
        News_SerialNumber: "",
        News_Name: "",
        News_Type: getQueryObject().News_Type
          ? getQueryObject().News_Type
          : "0",
        News_Type_SerialNumber: "",
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        News_Date: "",
        News_Main: "",
        Picture_URL: "",
        Detail_JSON: "",
      },
      loading: false,
    };
  },
  mounted() {
    $("title").text(this.News_Label + "添加");
    this.getData();
  },
  computed: {
    News_Label() {
      if (getQueryObject().News_Type) {
        this.form.News_Type = getQueryObject().News_Type;
      }
      let ObjNew_Type = this.News_Type.filter(
        (i) => i.value == this.form.News_Type
      )[0];
      return ObjNew_Type.label;
    },
  },
  methods: {
    handleBeforeUpload(file) {
      // 生成预览URL并添加到fileList中
      const reader = new FileReader();
      reader.onload = (e) => {
        //调用存储的接口放在onload中，存在异步操作
        const newFile = {
          name: file.name,
          url: e.target.result, // 预览URL
          uid: file.uid, //添加uid
          // 可以添加其他属性，如上传状态等
        };
        this.fileList.push(newFile);
        // for (let i = 0; i < this.fileList.length; i++) {
        //   this.fileList[i].uid = "D_" + this.fileList[i].uid;
        // }
        console.log(this.fileList);

        // return;
        $.ajax({
          // headers: requestHeaders(), // 确保这个函数返回正确的头部信息
          url: "https://service.kdddy.cn/donghuiForRequest/store/photo",
          // url: "http://192.168.10.79:8087/store/photo",
          type: "POST", // 注意HTTP方法应该大写
          contentType: "application/json", // 设置请求体的媒体类型为application/json
          data: JSON.stringify(this.fileList), // 将数据序列化为JSON字符串
          success: function (Result) {
            console.log(Result);
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest); // 确保这个函数在config/config.js中定义
          },
          dataType: "json", // 预期服务器返回的数据类型
        });
      };
      reader.readAsDataURL(file);
      // 返回false以阻止自动上传

      return false;
    },
    handleChange(file, fileList) {
      // 这个方法现在主要用于调试或处理其他上传后的逻辑
      // 注意：这里的fileList参数与:file-list绑定的fileList不是同一个对象
      // :file-list绑定的fileList是组件内部维护的，而这里的fileList是上传事件提供的
      console.log("Upload change event:", file, fileList);
    },
    getData() {
      const that = this;
      $.ajax({
        url: `${BASE_URL1}/NewTypeAll`,
        type: "POST",
        data: {
          Data: JSON.stringify({
            Add: {
              news_info: [that.form],
            },
          }),
        },
        success: function (data) {
          that.options = data;
        },
        dataType: "json",
      });
    },
    submitForm(formName) {
      console.log(this.form.News_Main);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this;
          $.ajax({
            // headers: requestHeaders(),
            // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
            url: "https://service.kdddy.cn/donghuiForRequest/getNowTime",
            type: "GET",
            success: function (Result) {
              _this.Atime(Result);
            },
            complete: function (XMLHttpRequest) {
              requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
            },
            dataType: "json",
          });
        }
      })

    },
    Atime(ARG_time) {
      console.log(ARG_time);
      console.log(ARG_time.Data);
      this.form.News_Date = ARG_time.Data;
      // return;
      this.form.Enterprise_Info_SerialNumber = sessionStorage.getItem(
        "Enterprise_Info_SerialNumber"
      );
      if (this.fileList.length > 0) {
        let base64Image = this.fileList[0].url;
        let dataIndex = base64Image.indexOf("data:");
        let base64Index = base64Image.indexOf(";base64,");
        let substring = base64Image.substring(dataIndex + 5, base64Index);
        let ls_split = substring.split("/");
        this.form.Picture_URL = this.fileList[0].uid + "." + ls_split[1];
      }

      console.log(this.form);

      let lArray = new Array();
      lArray.push(this.form);
      let lJSONObject_news_info = new Object();
      lJSONObject_news_info.news_info = lArray; //换表
      let lJSONObject_DataSet = new Object(); // Modify
      lJSONObject_DataSet.Add = lJSONObject_news_info; //换表
      const _this = this;
      $.ajax({
        // headers: requestHeaders(),
        // url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        url: "https://service.kdddy.cn/donghui/clientOperation/generalSaveForClient",
        type: "POST",
        data: {
          Data: JSON.stringify(lJSONObject_DataSet),
        },
        success: function (Result) {
          console.log(Result);
          if (Result.Status == "success") {
            _this.$message({
              message: "提交成功",
              type: "success",
            });
            setTimeout(() => {
              window.history.go(-1);
            }, 1500);
            // window.history.go(-1);
          } else {
            _this.$message.error("提交失败，请稍后再试");
          }
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest); //config/config.js 响应预检
        },
        dataType: "json",
      });
      return;
      const that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.loading = true;
          that.form.News_Date = getYMDHMSDate();

          if (that.type.length > 0) {
            let news_detail = [];
            this.type.forEach((item) => {
              news_detail.push({
                New_Type_SerialNumber: item[item.length - 1],
                Parent_SerialNumber: item[0],
              });
            });
            that.form["Children"] = { news_detail };
          }
          that.form.Detail_JSON = JSON.stringify(that.type);
          $.ajax({
            headers: requestHeaders(),
            url: `${BASE_URL2}/generalBusiness/generalSave`,
            type: "POST",
            data: {
              Data: JSON.stringify({
                Add: {
                  news_info: [that.form],
                },
              }),
            },
            success: function (res) {
              if (res.Status === "success") {
                that.$message.success("提交成功");
                window.history.go(-1);
              } else {
                that.$message.error("提交失败，请稍后再试");
              }
            },
            error: function () {
              that.$message.error("操作失败，请稍后再试");
            },
            complete: function (XMLHttpRequest) {
              that.loading = false;
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        } else {
          that.$message({
            message: sumberError,
            type: "warning",
          });
          return false;
        }
      });
    },
  },
});
